/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.meteocal.boundary;

import it.polimi.meteocal.control.UserManager;
import it.polimi.meteocal.entity.User;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;

@Named
@RequestScoped
public class RegistrationBean {

    private User user;
    private String console;
    @EJB
    private UserManager um;

    public RegistrationBean() {

    }

    public String getConsole() {
        return console;
    }

    public void setConsole(String console) {
        this.console = console;
    }

    public User getUser() {
        if (user == null) {
            user = new User();
        }
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    /**
     * set all the information about the new user
     *
     * @return index if don't exist another user with same email, an error
     * message otherwise
     */
    public String register() {
        if ("1".equals(console)) {
            user.setPublicCalendar(Boolean.TRUE);
        } else {
            user.setPublicCalendar(Boolean.FALSE);
        }
        if (!um.checkExistUser(user.getEmail())) {
            um.save(user);
            return "index";
        } else {
            System.out.println("user exist already");
            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "user already exist", null));
            return "";
        }
    }
}
